/*
 * @Author: liangshuchang
 * @Description:  司机端运单列表详情
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  NativeModules, BackHandler, Platform, DeviceEventEmitter
} from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import { my, myGray, iconMap, iconRightGray } from '../../../../image';
import { BackImage, msg, Header, Button } from '../../../../common';
import { mainBgColorLightGray, isAndroid } from '../../../../common/styles';
import {
  mainBgColorWhite,
  px2dp,
  screenWidth,

} from '../../../../common/styles/index';
import px2wp from '../../../../common/utils/px2wp';

import LoadInformation from '../../../../components/LoadInformation';
import GoodsInformation from '../../components/goods-information';
import DriverInformation from '../../components/driver-information';
import CarInformation from '../../components/car-information';
import TransportLine from '../../components/transport-line';
import ShowPic from '../../components/show_pic';
import obj from '../../../../common/utils/obj';
import supply from '../../../../api/supply';
import ImageViewer from '../../../../components/XmImageViewer';

const { Submit } = Button;

const isIphone = Platform.OS == 'ios';
export default class Details extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    headerLeft: (
      <TouchableOpacity
        activeOpacity={0.8}
        style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
          { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
        onPress={() => {
          const { xmHandleBack } = navigation.state.params;
          xmHandleBack();
        }}
      >
        <BackImage />
      </TouchableOpacity>
    ),
    headerTitle: '运单详情',
    // headerRight: (
    //   <TouchableOpacity
    //     activeOpacity={0.8}
    //     style={styles.headerLeft}
    //     onPress={() => {
    //       const { toDetailMap } = navigation.state.params
    //       toDetailMap()
    //     }}>
    //     <Image
    //       style={[styles.backImg]}
    //       source={iconMap}
    //       resizeMode="stretch"
    //     />
    //     <Text style={{ marginHorizontal: 6 }}>详情地图</Text>
    //   </TouchableOpacity>
    // )
  });

  constructor(props) {
    super(props);
    this.state = {
      detail: {},
      previewModal: false,
      images: []
    };
  }

  toDetailMap = () => {
    msg.emit('router: goToNext', {
      routeName: 'YdDetailMap',
    });
  }

  xmHandleBack = () => {
    msg.emit('router: refreshRoute', {
      routeName: 'ShipperTab',
    });
    msg.emit('router: goToNext', {
      routeName: 'ShipperOrder',
    });
  }

  getImgArr = (data, img, flag) => {
    data.forEach(ele => {
      ele.url = ele.pic,
      ele.adress = ele.addr;
      if (flag) {
        ele.type = '发货单';
      } else {
        ele.type = '收货单';
      }
      img.push(ele);
    });
  }

  render() {
    const { detail, previewModal, images } = this.state;
    const members = [];
    if (detail.loadingPics && detail.loadingPics.length) {
      this.getImgArr(detail.loadingPics, members, true);
    }
    if (detail.unloadingPics && detail.unloadingPics.length) {
      this.getImgArr(detail.unloadingPics, members, false);
    }
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: detail.wayBill && detail.wayBill.state === 2 ? '#fff' : mainBgColorLightGray }}>
        <View style={styles.container}>
          {detail.wayBill ? (
            <TransportLine detail={detail} />
          ) : null}
          <ScrollView style={{ marginTop: px2dp(292), flex: 1, width: '100%', }}>
            {/* marginBottom: detail.wayBill && detail.wayBill.state === 2 ? px2dp(110) : 0  */}
            {detail.wayBill ? (
              <GoodsInformation style={styles.mt20} wayBill={detail.wayBill} />
            ) : null}
            {
              detail.addrBegin ? (
                <LoadInformation detail={detail} />
              ) : null
            }
            {
              detail.driver ? (
                <DriverInformation style={styles.mt20} title='司机信息' onDriverDetail={() => this.onDriverDetail(true)} information={detail.driver} />
              ) : null
            }
            {
              detail.car ? (
                <CarInformation style={styles.mt20} information={detail.car} onCarDetail={this.onCarDetail} />
              ) : null
            }
            {/* 判断是否暂时回单 */}
            {
              members.length !== 0 ? (
                <View style={[styles.huizhi]}>
                  <View style={styles.hTitle}>
                    <Text style={{ color: '#333232', fontSize: px2dp(16) * 2 }}>回单信息</Text>
                  </View>
                  <TouchableOpacity
                    style={[{ flex: 1, overflow: 'hidden', }, styles.flexB]}
                    activeOpacity={0.8}
                    onPress={() => this.toPreView()}
                  >
                    <View style={{ flex: 1, flexDirection: 'row' }}>
                      {this.showImg(members)}
                    </View>
                    {isIphone && <View style={{ height: obj.STATUSBAR_HEIGHT + 10 }} />}
                    <View
                      style={[styles.flexB], { backgroundColor: '#fff', width: px2wp(16), height: '100%', alignItems: 'center', justifyContent: 'center' }}
                    >
                      <Image
                        style={[{ width: px2wp(16), height: px2wp(16), }, ]}
                        source={iconRightGray}
                        resizeMode='stretch'
                      />
                    </View>
                  </TouchableOpacity>

                </View>
              ) : null
            }
            {
              detail.wayBill && detail.wayBill.remark ? (
                <View style={[styles.huizhi]}>
                  <View>
                    <Text style={styles.hTitle}>备注信息</Text>
                  </View>
                  <View>
                    <Text style={{ fontSize: px2wp(16) }}>{detail.wayBill.remark}</Text>
                  </View>

                </View>
              ) : null
            }
            <View style={[styles.bot]} />
          </ScrollView>
          {/* {
            detail.wayBill && detail.wayBill.state === 2 ? (
              <View style={styles.purchaseBox}>
                <Submit
                  text='确认完成'
                  boxStyle={{
                    width: screenWidth - px2dp(120),
                    height: px2dp(80),
                    borderRadius: px2dp(8),
                    backgroundColor: '#BA914A',
                    borderWidth: 1,
                    borderColor: '#BA914A',
                  }}
                  onClick={() => { this.showModal(detail.wayBill.id, detail.wayBill) }}
                  btnTextStyle={{
                    color: '#fff'
                  }}
                />
              </View>
            ) : null
          } */}
          {
            previewModal ?
              <ImageViewer
                images={members}
                previewModal={previewModal}
                leftBackIcon={require('../../../../image/icons/back_white.png')}
                showViewModal={() => {
                  this.setState({
                    previewModal: false
                  });
                }}
              /> : null
          }
        </View>
      </SafeAreaView>
    );
  }

  // 展示回执信息的图片
  showImg = (data) => {
    return data.map((item, index) => {
      if (index <= 5) {
        return <Image
          style={styles.cardImg}
          source={{ uri: item.url }}
        />;
      }
    });
  }

  // 确认订单完成
  showModal = (data, item) => {
    supply.getWayBillState(data).then(res => {
      if (res.success) {
        let obj = {
          id: data,
          identity: 1 // 货主 1  车主 2  司机 3
        };
        if (item.state !== res.data) {
          msg.emit('app:tip', { text: '运单状态已更新，请刷新后重试' });
          this.detail(obj);
        } else {
          NativeModules.WindowModule.showWindow({ content: '确定该运单已完成吗？' }, (code) => {
            if (code == 1) {
              supply.finishWayBill({ id: data }).then(res => {
                if (res.success) {
                  this.detail(obj);
                } else {
                  msg.emit('app:tip', { text: res.msg });
                }
              });
            }
          });
        }
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    }).catch(err => {

    });
  }

  onDriverDetail = (flag) => {
    let data = flag ? this.state.detail.driver : this.state.detail.supplyOwner;
    msg.emit('router: goToNext', {
      routeName: 'DriverDetail',
      data: data,
      isDriver: true
    });
  }

  onCarDetail = () => {
    msg.emit('router: goToNext', {
      routeName: 'CarDetail',
      routerFrom: 'ShipperOrderDetail',
      data: this.state.detail.car,
      driver: this.state.detail.driver
    });
  }

  toReceipt() {
    msg.emit('router: goToNext', {
      routeName: 'ReceiptEdit',
    });
  }

  changeName = (data, name) => {
    for (let i in data) {
      if (i.indexOf(name) > -1 && i.split(name)[1]) {
        let neykey = (i.split(name)[1].substring(0, 1).toLowerCase() + i.split(name)[1].substring(1));
        data[neykey] = data[i] || '';
        delete data[i];
      }
    }
    return data;
  }

  toPreView = () => {
    this.setState({
      previewModal: true
    });
  }

  closePreview = () => {
    this.setState({
      previewModal: false
    });
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
    navigation.setParams({
      xmHandleBack: this.xmHandleBack,
      toDetailMap: this.toDetailMap
    });
    let obj = {
      id: data,
      identity: 1
    };
    this.detail(obj);

    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  componentWillUnmount() {
    if (Platform.OS == 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    this.xmHandleBack();
    return true;
  }

  detail = (obj) => {
    supply.detailsWayBill(obj).then(res => {
      if (res.success) {
        res.data.driver = this.changeName(res.data.driver, 'driver');
        this.setState({
          detail: res.data
        });
      } else {
        msg.emit('app:tip', { text: '获取失败' });
      }
    }).catch(err => {

    });
  }
}

const styles = StyleSheet.create({
  flexB: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    // paddingBottom:px2dp(24),
    height: 600,
    position: 'relative',
  },
  huizhi: {
    borderRadius: px2dp(20),
    marginLeft: px2dp(20),
    marginRight: px2dp(20),
    marginBottom: px2dp(20),
    marginTop: px2dp(20),
    backgroundColor: 'white',
    paddingLeft: px2dp(20),
    paddingRight: px2dp(20),
    paddingTop: px2dp(20),
    paddingBottom: px2dp(20)
  },
  hTitle: {
    paddingBottom: px2dp(20),
    borderBottomWidth: px2dp(2),
    borderBottomColor: '#E6E3E1',
    marginBottom: px2dp(20),
    color: '#333232',
    fontSize: px2dp(16) * 2
  },
  cardImg: {
    width: px2dp(120),
    height: px2dp(120),
    borderRadius: px2dp(8),
    marginRight: px2dp(10) * 2,
  },
  purchaseBox: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    width: screenWidth,
    height: px2dp(110),
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  bot: {
    height: px2dp(50),
    width: '100%'
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    color: '#999896',
  },
  backImg: {
    width: px2dp(34),
    height: px2dp(34),
    marginLeft: px2dp(24),
  },
});
